package jumpingnotes.restlet.resource;

import static jumpingnotes.restlet.ErrorCode.NO_PERMISSION;
import static jumpingnotes.restlet.ErrorCode.OBJECT_NOT_FOUND;
import static jumpingnotes.restlet.ErrorCode.SERVER_INTERNAL_ERROR;

import java.util.ArrayList;
import java.util.List;

import jumpingnotes.model.entity.Book;
import jumpingnotes.model.entity.Member;
import jumpingnotes.restlet.JsonMapping;

import org.json.JSONObject;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;

public class MemberFavoritesResource extends BaseResource
{
	private Member member = null;

	@Override
	public void init(Context context, Request request, Response response)
	{
		super.init(context, request, response);

		getVariants().add(new Variant(MediaType.APPLICATION_JSON));

		try
		{
			sessionId = (String) getRequest().getAttributes().get("sessionId");
			checkPermission();

			if (hasPermission())
			{
				// URL: "/members/{memberId}/favorites"
				String memberIdStr = (String) getRequest().getAttributes().get("memberId");

				if ("me".equalsIgnoreCase(memberIdStr))
				{
					String email = session.getEmail();
					member = service.findMemberByEmail(email);
				}
				else
				{
					int memberId = Integer.parseInt(memberIdStr);
					member = service.findMemberById(memberId);
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public Representation represent(Variant variant) throws ResourceException
	{
		if (!hasPermission())
		{
			return createErrorRepresentation(NO_PERMISSION);
		}

		if (member == null)
		{
			return createErrorRepresentation(OBJECT_NOT_FOUND);
		}

		try
		{
			List<Book> bookList = service.findFavoriteBookByMemberId(member.getMemberId());

			List<JSONObject> bookJsonList = new ArrayList<JSONObject>();
			for (Book book : bookList)
			{
				JSONObject bookJson = JsonMapping.map(book);
				bookJsonList.add(bookJson);
			}

			JSONObject booksJson = new JSONObject();
			booksJson.put("books", bookJsonList);

			return createJsonRepresentation(booksJson);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return createErrorRepresentation(SERVER_INTERNAL_ERROR);
		}
	}
}
